﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Sitecore.Data.Items;
using System.Data;
using Workflow.Alerts.DAL;
using System.Text;
using System.Globalization;
using Workflow.Alerts.Utils;
using workflow.Dal;


namespace Workflow.Alerts
{
    public class GridPresenter : ListPresenter
    {
        #region members
        private readonly IMainListView view;
        #endregion

        #region constructor
        public GridPresenter(IMainListView _view)
            : this(_view, null)
        { }

        public GridPresenter(IMainListView _view, ISessionProvider session)
            : base(_view, session)
        {
            view = base.GetView<IMainListView>();
            view.OnListLoad += view_OnLoad;
            view.OnChangeStatus += ChangeStatus;
            view.OnSave += Save;
            view.OnRequestExcelForInvoice += GetInvoice;
            view.SendToArchiveList += view_SendToArchiveList;
            view.OnRemoveSelection += RemoveSelection;
            model = new MainListDAL();
        }

        #endregion

        #region private methods

        protected override void view_OnLoad()
        {
            base.view_OnLoad();
            var alerts = GetList();

            view.Alerts = AddColumns((EstateDataSet.ListAlertRow[])alerts);
            view.ScreenName = Translate.Words.ContainsKey(Sitecore.Context.Item.Name) ?
                Translate.Words[Sitecore.Context.Item.Name] : Sitecore.Context.Item.Name;
        }

        private EstateDataSet.ContactAlertsDataTable GetContactAlerts()
        {
            SetWorkflowFilter(Utils.Utils.GetCurrentItem());
            return model.GetContactAlerts(new WorkflowFilterSql(workflowFilter));
        }

        private DataRow[] AddColumns(EstateDataSet.ListAlertRow[] listAlertArr)
        {
            foreach (EstateDataSet.ListAlertRow row in listAlertArr)
            {
                row.alerttypename = WorkflowEnums.AlertTypeList[row.alerttype];
                row.activitytypename = WorkflowEnums.ActivityTypeList[row.activitytype];
            }

            //get herstel alerts
            if(Sitecore.Context.Item.Name==WorkflowConstants.Executed&&
                CurrentUser.Type==WorkflowEnums.UserType.Municipality){
                    DataTable herstelAlerts = model.GetHerstelAlerts(new WorkflowFilterSql(workflowFilter));
                    foreach (DataRow herstelAlertRow in herstelAlerts.Rows)
                    {
                        var alertid = Int32.Parse(herstelAlertRow["alertid"].ToString());
                        var alert = listAlertArr.Where(a => a.id == alertid).FirstOrDefault();
                        if (alert != null)
                            alert.isherstel = true;
                    }
            }


            return listAlertArr;
        }

        private void ChangeStatus(Int32 id, WorkflowEnums.Status newStatus, WorkflowEnums.Status oldStatus)
        {
            using (WorkflowEntitySet context = new WorkflowEntitySet())
            {
                List<Alert> tempChanges = TempChanges;
                var alert = tempChanges.Where(a => a.id == id).FirstOrDefault();
                if (alert != null)
                    tempChanges.Remove(alert);

                alert = context.Alert.Where(a => a.id == id).First();
                alert.currentstatus = (int)newStatus;
                tempChanges.Add(alert);
                TempChanges = tempChanges;
            }
        }

        private void RemoveSelection(int alertid)
        {
            List<Alert> tempChanges = TempChanges;
            var alert = tempChanges.Where(a => a.id == alertid).FirstOrDefault();
            if (alert != null)
                tempChanges.Remove(alert);
            TempChanges = tempChanges;


            //if (Changes != null && Changes.Rows.Count > 0)
            //{
            //    var alert = Changes.FindByid(alertid);
            //    if (alert != null)
            //    {
            //        Changes.Rows.Remove(alert);
            //        Changes.AcceptChanges();
            //    }
            //}
        }

        private DataTable GetInvoice(bool archive, List<string> ids, WorkflowEnums.Status? status, WorkflowEnums.InvoiceFormat format)
        {
            WorkflowFilter filter = new WorkflowFilter()
            {
                MunicipalityId = CurrentUser.TypeId,
                Archive = archive,
                CurrentStatus = status,
                Ids = ids
            };

            switch (format)
            {
                case WorkflowEnums.InvoiceFormat.CSV:
                    return model.GetCsvForInvoice(new WorkflowFilterSql(filter));

                case WorkflowEnums.InvoiceFormat.XLS:
                    return model.GetExcelForInvoice(new WorkflowFilterSql(filter));

                default:
                    return null;
            }
        }

        private void view_SendToArchiveList(List<string> listOfId)
        {
            using (WorkflowEntitySet context = new WorkflowEntitySet())
            {
                foreach (var id in listOfId)
                {
                    int alertId = Int32.Parse(id);
                    var alert = context.Alert.Where(a => a.id == alertId).First();
                    if (alert.currentstatus == (int)WorkflowEnums.Status.AcceptedPartially)
                    {
                        alert.archived = true;
                    }
                }
                context.SaveChanges();
            }
        }

        private void Save()
        {
            var tempChanges = TempChanges;
            if (tempChanges.Any())
            {
                var contacts = GetContactAlerts();
                SavePresenter saveHelper = new SavePresenter(null, Session);
                using (WorkflowEntitySet context = new WorkflowEntitySet())
                {
                    foreach (Alert tempAlert in tempChanges)
                    {
                        switch ((WorkflowEnums.Status)tempAlert.currentstatus)
                        {
                            case WorkflowEnums.Status.Approved:
                            case WorkflowEnums.Status.PartiallyApproved:
                            case WorkflowEnums.Status.Rejected:
                                {
                                    saveHelper.SaveNewAlert(tempAlert, context);
                                }
                                break;

                            case WorkflowEnums.Status.Accepted:
                            case WorkflowEnums.Status.AcceptedPartially:
                            case WorkflowEnums.Status.Declined:
                                {
                                    saveHelper.SaveExecutedAlert(tempAlert, context);
                                }
                                break;
                            case WorkflowEnums.Status.Sent:
                                saveHelper.SaveSentAlert(tempAlert, context);
                                break;

                        }

                        var contact = contacts.FindByid(tempAlert.id);
                        SendNotification(contact, tempAlert.currentstatus, tempAlert.id.ToString());
                    }

                    context.SaveChanges();
                }

                TempChanges = null;
                Session["TempAlertMaterials"] = null;
            }
        }

        private void SendNotification(EstateDataSet.ContactAlertsRow contact, int status, string alertid)
        {
            if (CurrentUser.Type == WorkflowEnums.UserType.Municipality)
            {
                if ((WorkflowEnums.Status)status == WorkflowEnums.Status.Accepted || (WorkflowEnums.Status)status == WorkflowEnums.Status.AcceptedPartially)
                {
                    //save invoice data
                    WorkflowFilter filter = new WorkflowFilter()
                    {
                        AlertId = Int32.Parse(alertid)
                    };
                    AlertViewDAL dal = new AlertViewDAL();
                    dal.PrepareInvoiceData(new WorkflowFilterSql(filter));
                }

                if (contact != null && contact.nonotification)
                    Notification.SendNotification(alertid, status, contact);
            }
            else
            {
                if (contact != null &&
                    contact.munnotification &&
                    status != (Int32)WorkflowEnums.Status.Deleted &&
                    status != (Int32)WorkflowEnums.Status.Sent)
                    Notification.SendNotification(alertid, status, contact);
            }
        }

        #endregion
    }
}

